﻿namespace FFF.Test.DataAccess.Framework
{
    using System.IO;
    using Abp.EntityFrameworkCore;
    using Abp.EntityFrameworkCore.Configuration;
    using Abp.Modules;
    using Abp.Reflection.Extensions;
    using Microsoft.EntityFrameworkCore;
    using Microsoft.Extensions.Configuration;
    using FFF.Test.DataAccess.Framework.Configuration;
    using FFF.Test.Entity;
    using FFF.Test.Util.Configuration;
    using FFF.Test.Util.Consts;
    using Z.EntityFramework.Extensions;

    /// <summary>
    /// 数据层初始化
    /// </summary>
    [DependsOn(
        typeof(YdmAbpEntityModule),
        typeof(AbpEntityFrameworkCoreModule))]
    public class YdmAbpDataAccessModule : AbpModule
    {
        /// <summary>
        /// 用于测试用例
        /// </summary>
        public bool SkipDbContextRegistration { get; set; }

        /// <summary>
        /// 用于测试用例
        /// </summary>
        public bool SkipDbSeed { get; set; }

        /// <summary>
        /// 初始化配置
        /// </summary>
        public override void PreInitialize()
        {
        }

        /// <summary>
        /// 初始化依赖注入
        /// </summary>
        public override void Initialize()
        {
            // 配置Abp使用的数据连接字符串 有依赖注入优先使用依赖注入
            this.Configuration.DefaultNameOrConnectionString = AppConfigConsts.ConStr;

            // 初始化数据库连接配置
            base.Configuration.Modules.AbpEfCore().AddDbContext<MyDbContext>(options =>
            {
                if (options.ExistingConnection != null)
                {
                    DbContextOptionsConfigurer.Configure(options.DbContextOptions, options.ExistingConnection);
                }
                else
                {
                    DbContextOptionsConfigurer.Configure(options.DbContextOptions, options.ConnectionString);
                }
            });

            // 配置z.entity的批量连接
            EntityFrameworkManager.ContextFactory = context =>
            {
                DbContextOptionsBuilder<MyDbContext> optionsBuilder = new DbContextOptionsBuilder<MyDbContext>();
                DbContextOptionsConfigurer.Configure(optionsBuilder, AppConfigConsts.ConStr);
                return new MyDbContext(optionsBuilder.Options, base.IocManager);
            };

            EntityFrameworkManager.PreBulkSaveChanges = context =>
            {
                System.Collections.Generic.IEnumerable<Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry> entries = context.ChangeTracker.Entries();

                // DbSaveConfiguration.BeforeSaveInitData(entries, base.IocManager);
            };

            this.IocManager.RegisterAssemblyByConvention(typeof(YdmAbpDataAccessModule).GetAssembly());

            // 全局拦截
            // DbInterception.Add(new EFCommandInterceptor());
            // DbInterception.Add(new EFConnectionInterceptor());

            // DbInterception.Add(new EFTransactionInterceptor());
        }
    }
}
